package com.jinzhi.jzweb.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzsynthesize.ExcelVo.ResultEnterVo;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.pojo.ItemBankVo;
import com.jinzhi.jzweb.pojo.ItemBankVoxzy;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * <pre>
 * 题库表
 *
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/itemBank")
public class ItemBankController extends BaseController {
    @Autowired
    private ItemBankService itemBankService;
    @Autowired
    private UserService userService;
    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private ExaminationGradingService examinationGradingService;

    @GetMapping()
    @RequiresPermissions("jzweb:itemBank:itemBank")
    String ItemBank(Model model) {
        model.addAttribute("cprofileIds", certificateProfileService.selByAll());
        return "jzweb/itemBank/itemBank";
    }

    @Log("选择证书的所属知识点")
    @ResponseBody
    @GetMapping("/byKnowledges")
    public Result<?> distributionSecond(String cprofileId) {
        if (StringUtils.isNotBlank(cprofileId)) {
            List<Map<Object, Object>> mapsre = new ArrayList<>();
            //只查询最上级的知识点
            List<KnowledgePointsDO> knowledgePointsDOS = knowledgePointsService.findByKv("profile_id", Long.parseLong(cprofileId), "pid", 0);
            if (knowledgePointsDOS != null && knowledgePointsDOS.size() > 0) {
                for (KnowledgePointsDO knowledgePointsDO : knowledgePointsDOS) {
                    //这里可能会因为证书等级的不同，出现知识点名称相同的情况
                    Map map = new HashMap();
                    map.put("id", knowledgePointsDO.getId());
                    map.put("name", knowledgePointsDO.getName());
                    mapsre.add(map);
                }
            }

            return Result.ok(mapsre);

        }
        return Result.fail("请先选择证书！");
    }

    @Log("选择知识点的适用等级")
    @ResponseBody
    @GetMapping("/byGrades")
    public Result<?> byGrades(String knowId) {
        if (StringUtils.isNotBlank(knowId)) {
            //只查询最上级的知识点
            KnowledgePointsDO knowledgePointsDOS = knowledgePointsService.selectById(Long.parseLong(knowId));
            return Result.ok(knowledgePointsDOS.getGrade());
        }
        return Result.fail("请先选择知识点！");
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:itemBank:itemBank")
    public Result<Page<ItemBankDO>> list(ItemBankDO itemBankDTO) {
        Wrapper<ItemBankDO> wrapper = new EntityWrapper<ItemBankDO>().orderBy("id", false);
        if (itemBankDTO.getItemBankType() != null) {
            wrapper.eq("item_bank_type", itemBankDTO.getItemBankType());
        }
        if (itemBankDTO.getTopicTypes() != null) {
            wrapper.eq("topic_types", itemBankDTO.getTopicTypes());
        }
        if (itemBankDTO.getState() != null) {
            wrapper.eq("state", itemBankDTO.getState());
        }
        if (itemBankDTO.getType() != null) {
            wrapper.eq("type", itemBankDTO.getType());
        }
        if (itemBankDTO.getTopicContent() != null) {
            wrapper.like("topic_content", itemBankDTO.getTopicContent());
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(itemBankDTO.getProfileName())) {
            Wrapper<CertificateProfileDO> cerWrapper = new EntityWrapper<CertificateProfileDO>().like("name", itemBankDTO.getProfileName());
            List<CertificateProfileDO> certificateProfileDOS = certificateProfileService.selectList(cerWrapper);
            String str = "";
            for (CertificateProfileDO certificateProfileDO : certificateProfileDOS) {
                str = str + certificateProfileDO.getId() + ",";
            }
            wrapper.and();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
                wrapper.in("profile_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("profile_id", null);
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(itemBankDTO.getKpointsName())) {
            Wrapper<KnowledgePointsDO> knWrapper = new EntityWrapper<KnowledgePointsDO>().like("name", itemBankDTO.getKpointsName()).and().eq("pid", 0);
            List<KnowledgePointsDO> knowledgePointsDOS = knowledgePointsService.selectList(knWrapper);
            String str = "";
            for (KnowledgePointsDO knowledgePointsDO : knowledgePointsDOS) {
                str = str + knowledgePointsDO.getId() + ",";
            }
            wrapper.and();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
                wrapper.in("kpoints_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("kpoints_id", null);
            }
        }

        Page<ItemBankDO> page = itemBankService.selectPage(getPage(ItemBankDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ItemBankDO obj = (ItemBankDO) page.getRecords().get(i);
            if (obj.getKpointsId() != null) {
                KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(obj.getKpointsId());
                if (knowledgePointsDO != null) {
                    obj.setKpointsName(knowledgePointsDO.getName());
                }
            }
            if (obj.getProfileId() != null) {
                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(obj.getProfileId());
                if (certificateProfileDO != null) {
                    obj.setProfileName(certificateProfileDO.getName());
                }
            }
            if (obj.getCreaterId() != null) {
                UserDO userDO = userService.selectById(obj.getCreaterId());
                if (userDO != null) {
                    obj.setCreaterName(userDO.getUsername());
                }
            }
            if (obj.getUpdaterId() != null) {
                UserDO userDO = userService.selectById(obj.getUpdaterId());
                if (userDO != null) {
                    obj.setUpdaterName(userDO.getUsername());
                }
            }
            if (obj.getCheckerId() != null) {
                UserDO userDO = userService.selectById(obj.getCheckerId());
                if (userDO != null) {
                    obj.setCheckerName(userDO.getUsername());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }
    @Log("导出题目信息")
    @RequestMapping("/download")
//    @RequiresPermissions("synthesizeWeb:resultEnter:import")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response ,HttpServletRequest req) {
        Wrapper<ItemBankDO> wrapper = new EntityWrapper<ItemBankDO>().orderBy("id", false);

        List<ItemBankDO> itemBankDOS = itemBankService.selectList(wrapper);

        List<ItemBankVoxzy> list = new ArrayList();
        for (int i = 0; i < itemBankDOS.size(); i++) {
            ItemBankDO obj = itemBankDOS.get(i);
            ItemBankVoxzy vo=new ItemBankVoxzy();
            BeanUtils.copyProperties(obj,vo);
            if (obj.getKpointsId() != null) {
                KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(obj.getKpointsId());
                if (knowledgePointsDO != null) {
                    vo.setKpointsNames(knowledgePointsDO.getName());
                }
            }
            if (obj.getProfileId() != null) {
                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(obj.getProfileId());
                if (certificateProfileDO != null) {
                    vo.setProfileName(certificateProfileDO.getName());
                }
            }
//            if (obj.getCreaterId() != null) {
//                UserDO userDO = userService.selectById(obj.getCreaterId());
//                if (userDO != null) {
//                    vo.setCreaterName(userDO.getUsername());
//                }
//            }
//            if (obj.getUpdaterId() != null) {
//                UserDO userDO = userService.selectById(obj.getUpdaterId());
//                if (userDO != null) {
//                    obj.setUpdaterName(userDO.getUsername());
//                }
//            }
//            if (obj.getCheckerId() != null) {
//                UserDO userDO = userService.selectById(obj.getCheckerId());
//                if (userDO != null) {
//                    obj.setCheckerName(userDO.getUsername());
//                }
//            }
            list.add(vo);
        }

        //导出操作
        EasyPoiUtil.exportExcel(list, "证书练习题库", "证书练习题库", ItemBankVoxzy.class, "证书练习题库", response);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:itemBank:add")
    String add(Model model) {
        model.addAttribute("certificateProfile", certificateNewsService.selByProfile());
        return "jzweb/itemBank/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:itemBank:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        model.addAttribute("certificateProfile", certificateNewsService.selByProfile());
        ItemBankDO itemBank = itemBankService.selectById(id);
        model.addAttribute("itemBank", itemBank);
        return "jzweb/itemBank/edit";
    }

    @GetMapping("/info/{id}")
    @RequiresPermissions("jzweb:itemBank:itemBank")
    String info(@PathVariable("id") Long id, Model model) {
        ItemBankDO itemBankDO = itemBankService.selectById(id);
        if (itemBankDO != null) {
            if (itemBankDO.getKpointsId() != null) {
                KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(itemBankDO.getKpointsId());
                if (knowledgePointsDO != null) {
                    itemBankDO.setKpointsName(knowledgePointsDO.getName());
                }
            }
            if (itemBankDO.getProfileId() != null) {
                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(itemBankDO.getProfileId());
                if (certificateProfileDO != null) {
                    itemBankDO.setProfileName(certificateProfileDO.getName());
                }
            }
            if (itemBankDO.getCreaterId() != null) {
                UserDO userDO = userService.selectById(itemBankDO.getCreaterId());
                if (userDO != null) {
                    itemBankDO.setCreaterName(userDO.getUsername());
                }
            }
            if (itemBankDO.getUpdaterId() != null) {
                UserDO userDO = userService.selectById(itemBankDO.getUpdaterId());
                if (userDO != null) {
                    itemBankDO.setUpdaterName(userDO.getUsername());
                }
            }
            if (itemBankDO.getCheckerId() != null) {
                UserDO userDO = userService.selectById(itemBankDO.getCheckerId());
                if (userDO != null) {
                    itemBankDO.setCheckerName(userDO.getUsername());
                }
            }
        }
        model.addAttribute("itemBankDO", itemBankDO);
        return "jzweb/itemBank/info";
    }

    @Log("添加题库表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:itemBank:add")
    public Result<String> save(ItemBankDO itemBank) {
        //根据题目内容、证书概况id、题库类型、题目类型、类型、等级判断
        ItemBankDO itemBankDO = itemBankService
                .findOneByKv("topic_content", itemBank.getTopicContent(), "profile_id", itemBank.getProfileId(),
                        "item_bank_type", itemBank.getItemBankType(), "topic_types", itemBank.getTopicTypes(), "type", itemBank.getType());
        if (itemBankDO != null) {
            return Result.fail("题目已存在，请检查！（如适用等级不一致，直接编辑调整即可）");
        } else {
            if (itemBank.getTopicTypes() == 3) {
                itemBank.setType(1);
                //技能题导入时，会统一调至综合知识点
                KnowledgePointsDO knowledgePointsDO1 = knowledgePointsService
                        .findOneByKv("profile_id", itemBank.getProfileId(), "name", "综合知识点", "pid", 0);
                itemBank.setKpointsId(knowledgePointsDO1.getId());
            } else {
                itemBank.setType(0);
            }
            //修改文件路径
            if(StringUtils.isNotBlank(itemBank.getFileRoute())){
                itemBank.setResourceUrl(itemBank.getFileRoute());
            }
            itemBank.setCreaterId(this.getUserId());
            itemBank.setUpdaterId(this.getUserId());
            itemBankService.insert(itemBank);
            return Result.ok();
        }
    }

    @Log("修改题库表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:itemBank:edit")
    public Result<String> update(ItemBankDO itemBank) {
        //根据题目内容、证书概况id、题库类型、题目类型、类型、等级判断
        List<ItemBankDO> itemBankDO = itemBankService
                .findByKv("topic_content", itemBank.getTopicContent(), "profile_id", itemBank.getProfileId(),
                        "item_bank_type", itemBank.getItemBankType(), "topic_types", itemBank.getTopicTypes(), "type", itemBank.getType());
        if (itemBankDO != null && itemBankDO.size() > 0) {
            if (itemBankDO.size() == 1) {
                if (itemBankDO.get(0).getId().equals(itemBank.getId())) {
                    if (itemBank.getTopicTypes() == 3) {
                        itemBank.setType(1);
                        //技能题导入时，会统一调至综合知识点
                        KnowledgePointsDO knowledgePointsDO1 = knowledgePointsService
                                .findOneByKv("profile_id", itemBank.getProfileId(), "name", "综合知识点", "pid", 0);
                        itemBank.setKpointsId(knowledgePointsDO1.getId());
                    } else {
                        itemBank.setType(0);
                    }
                    //修改文件路径
                    if(StringUtils.isNotBlank(itemBank.getFileRoute())){
                        itemBank.setResourceUrl(itemBank.getFileRoute());
                    }
                    itemBank.setUpdaterId(this.getUserId());
                    boolean update = itemBankService.updateById(itemBank);
                    return update ? Result.ok() : Result.fail();
                }
            }
            return Result.fail("题目已存在，请检查！（如适用等级不一致，直接编辑调整即可）");
        } else {
            if (itemBank.getTopicTypes() == 3) {
                itemBank.setType(1);
                //技能题导入时，会统一调至综合知识点
                KnowledgePointsDO knowledgePointsDO1 = knowledgePointsService
                        .findOneByKv("profile_id", itemBank.getProfileId(), "name", "综合知识点", "pid", 0);
                itemBank.setKpointsId(knowledgePointsDO1.getId());
            } else {
                itemBank.setType(0);
            }
            //修改文件路径
            if(StringUtils.isNotBlank(itemBank.getFileRoute())){
                itemBank.setResourceUrl(itemBank.getFileRoute());
            }
            itemBank.setUpdaterId(this.getUserId());
            boolean update = itemBankService.updateById(itemBank);
            return update ? Result.ok() : Result.fail();
        }
    }

    @Log("删除题库表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:itemBank:remove")
    public Result<String> remove(Long id) {
        boolean b = itemBankService.deleteById(id);
        if (b) {
            //删除评分表信息
            List<ExaminationGradingDO> examinationGradingDOS = examinationGradingService.findByKv("ibank_id", id);
            if (examinationGradingDOS != null && examinationGradingDOS.size() > 0) {
                List<Long> ids = new ArrayList<>();
                for (int j = 0; j < examinationGradingDOS.size(); j++) {
                    ids.add(examinationGradingDOS.get(j).getId());
                }
                examinationGradingService.deleteBatchIds(ids);
            }
        }
        return Result.ok();
    }

    @Log("批量删除题库表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:itemBank:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        boolean b = itemBankService.deleteBatchIds(Arrays.asList(ids));
        if (b) {
            for (int i = 0; i < ids.length; i++) {
                //删除评分表信息
                List<ExaminationGradingDO> examinationGradingDOS = examinationGradingService.findByKv("ibank_id", ids[i]);
                if (examinationGradingDOS != null && examinationGradingDOS.size() > 0) {
                    List<Long> idss = new ArrayList<>();
                    for (int j = 0; j < examinationGradingDOS.size(); j++) {
                        idss.add(examinationGradingDOS.get(j).getId());
                    }
                    examinationGradingService.deleteBatchIds(idss);
                }
            }
        }

        return Result.ok();
    }

    @Log("审核")
    @PostMapping("/review")
    @ResponseBody
    @RequiresPermissions("jzweb:itemBank:review")
    public Result<String> review(@RequestParam("ids[]") Long[] ids, Integer state, String remark) {
        if (state.equals(2) || state.equals(1)) {
            int i = 0;
            for (Long id : ids) {
                ItemBankDO itemBankDO = itemBankService.selectById(id);
                if (itemBankDO != null) {
                    if (itemBankDO.getTopicTypes() == 3) {
                        List<ExaminationGradingDO> examinationGradingDOS = examinationGradingService.findByKv("ibank_id", id);
                        if (examinationGradingDOS == null || examinationGradingDOS.size() == 0) {
                            return Result.fail("实操题：（" + itemBankDO.getTopicContent() + "）还没有添加评分表信息，请添加后审核！");
                        }
                    }

                    itemBankDO.setState(state);
                    itemBankDO.setCheckerId(this.getUserId());
                    itemBankDO.setCheckerDate(new Date());
                    if (state.equals(2)) {
                        itemBankDO.setRemark(remark);//未通过，添加备注
                    } else {
                        itemBankDO.setRemark("");//审核通过，清空备注
                    }
                    boolean b = itemBankService.updateById(itemBankDO);
                    if (b) {
                        i++;
                    } else {
                        break;
                    }
                }
            }
            if (i == ids.length) {
                return Result.build(0, "已成功审核：" + i + "条数据");
            } else {
                return Result.fail("审核状态修改失败！");
            }
        } else {
            return Result.fail("审核状态修改失败！");
        }
    }


    /**
     * 下载导入模板
     *
     * @param response
     */
    @RequestMapping("/downloadImportTemplate")
    @RequiresPermissions("jzweb:itemBank:import")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response) {
        List<ItemBankVo> list = new LinkedList<>();
        //导出操作
        EasyPoiUtil.exportExcel(list, "题库题目信息导入模板（技能题导入时，会统一调至综合知识点）", "题库题目信息导入模板", ItemBankVo.class, "题库题目信息导入模板", response);
    }

    /**
     * 题目信息导入
     *
     * @param file excel文件
     */
    @Log("题目信息导入")
    @PostMapping("/import")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:itemBank:import")
    public Result<?> importExcel(@RequestParam("file") MultipartFile file, String cprofileId, String kpointsId) {
        //---------------------------------检测导入信息及条件-----------------------------------------
        //第一步--判断文件格式
        if (!"application/vnd.ms-excel".equals(file.getContentType())) {
            return Result.fail("文件格式错误，请选择.xls文件");
        }

        //第二步--解析文件获得数据
        List<ItemBankVo> list = EasyPoiUtil.importExcel(file, 1, 1, ItemBankVo.class);
        if (list.size() == 0) {
            return Result.fail("Excel数据为空，请完善");
        }

        //---------------------------------验证数据并导入-----------------------------------------
        //数据该表第三行，第一行标题，第二行表头
        int startRow = 3;
        int cout = 1;//错误信息计数
        List<ItemBankDO> bankDOList = new ArrayList<>();
        List<ErrorCodeVo> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            StringBuilder sb = new StringBuilder();
            //第一步验证是否存在空值
            if (StringUtils.isBlank(list.get(i).getGrade())) {
                sb.append("第" + (i + startRow) + "行适用证书等级未填写，请完善！" + ";");
            } else {
                if (StringUtils.isBlank(list.get(i).getItemBankType())) {
                    sb.append("第" + (i + startRow) + "行题库类型未填写，请完善！" + ";");
                } else {
                    if (StringUtils.isBlank(list.get(i).getTopicTypes())) {
                        sb.append("第" + (i + startRow) + "行题目类型未填写，请完善！" + ";");
                    } else {
                        if (StringUtils.isBlank(list.get(i).getTopicContent())) {
                            sb.append("第" + (i + startRow) + "行题目内容未填写，请完善！" + ";");
                        } else {
                            //第四步排重验证（自身比较）
                            for (int j = 0; j < list.size(); j++) {
                                if (i != j) {
                                    if (list.get(i).getTopicContent().trim().equals(list.get(j).getTopicContent().trim())) {
                                        sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行题目内容重复，重复值：" + list.get(i).getTopicContent().trim() + ";");
                                    }
                                }
                            }

                            int itembankType = 9;
                            int topicType = 9;
                            int type;
                            //题库类型（0练习题，1考试题）
                            if (list.get(i).getItemBankType().equals("练习题")) {
                                itembankType = 0;
                            } else if (list.get(i).getItemBankType().equals("考试题")) {
                                itembankType = 1;
                            } else {
                                sb.append("第" + (i + startRow) + "行题库类型填写错误，请按照示例填写！" + ";");
                            }

                            //题目类型（0单选，1多选，2判断，3实操）
                            if (list.get(i).getTopicTypes().equals("单选")) {
                                topicType = 0;
                                if(StringUtils.isBlank(list.get(i).getOptionsA())||StringUtils.isBlank(list.get(i).getOptionsB())||StringUtils.isBlank(list.get(i).getOptionsC())||StringUtils.isBlank(list.get(i).getOptionsD())){
                                    sb.append("第" + (i + startRow) + "行选项未填写完整，请按照示例填写！" + ";");
                                }
                            } else if (list.get(i).getTopicTypes().equals("多选")) {
                                topicType = 1;
                                if(StringUtils.isBlank(list.get(i).getOptionsA())||StringUtils.isBlank(list.get(i).getOptionsB())||StringUtils.isBlank(list.get(i).getOptionsC())||StringUtils.isBlank(list.get(i).getOptionsD())){
                                    sb.append("第" + (i + startRow) + "行选项未填写完整，请按照示例填写！" + ";");
                                }
                            } else if (list.get(i).getTopicTypes().equals("判断")) {
                                topicType = 2;
                                if(StringUtils.isBlank(list.get(i).getOptionsA())||StringUtils.isBlank(list.get(i).getOptionsB())){
                                    sb.append("第" + (i + startRow) + "行选项未填写完整，请按照示例填写！" + ";");
                                }
                            } else if (list.get(i).getTopicTypes().equals("实操")) {
                                topicType = 3;
                            } else {
                                sb.append("第" + (i + startRow) + "行题目类型填写错误，请按照示例填写" + ";");
                            }

                            if (topicType == 3) {
                                type = 1;//技能
//                                if (StringUtils.isBlank(list.get(i).getTopicAnalysis())) {
//                                    sb.append("第" + (i + startRow) + "行题目解析未填写，请完善！" + ";");
//                                }
                            } else {
                                type = 0;//理论
                                if (StringUtils.isBlank(list.get(i).getRightKey())) {
                                    sb.append("第" + (i + startRow) + "行正确答案未填写，请完善！" + ";");
                                }
//                                //答案选项判断
//                                if (StringUtils.isBlank(list.get(i).getOption())) {
//                                    sb.append("第" + (i + startRow) + "行答案选项未填写，请完善！" + ";");
//                                }
                            }

                            //KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(Long.parseLong(list.get(i).getKnowledge()));
//                            Wrapper<KnowledgePointsDO> uWrapper = new EntityWrapper();
//                            //uWrapper.like("name",list.get(i).getKnowledge());
//                          List <KnowledgePointsDO> list2=  knowledgePointsService.selectList(uWrapper);
//                          if(list2.size()==0){
//
//                              sb.append("第" + (i + startRow) + "在数据库中未找到匹配知识点！" + ";");
//                          }
//                            kpointsId=list2.get(0).getId().toString();
//                            String[] gradearr = list.get(i).getGrade().split(",");
//                            for (int jj = 0; jj < gradearr.length; jj++) {
//                                if (!list2.get(0).getGrade().contains(gradearr[jj])) {
//                                    sb.append("第" + (i + startRow) + "行适用证书等级已超过知识点的适用等级，请检查后重试！" + ";");
//                                }
//                            }

                            if (itembankType != 9 && topicType != 9) {
                                //第六步排重验证（和数据库比较），根据题目内容、证书概况id、题库类型、题目类型、类型、等级判断
                                ItemBankDO itemBankDO = itemBankService
                                        .findOneByKv("topic_content", list.get(i).getTopicContent().trim(), "profile_id", Long.parseLong(cprofileId),
                                                "item_bank_type", itembankType, "topic_types", topicType, "type", type, "grade", list.get(i).getGrade());
                                if (itemBankDO != null) {
                                    sb.append("第" + (i + startRow) + "行题目已存在，请检查！" + ";");
                                } else {
                                    ItemBankDO itemBankDO1 = new ItemBankDO();
                                    itemBankDO1.setGrade(list.get(i).getGrade());//适用证书等级(高级,中级,初级)
                                    if (type == 0) {
                                        itemBankDO1.setKpointsId(Long.parseLong(kpointsId));//知识点id
                                        itemBankDO1.setCheckerId(this.getUserId());//审核人
                                        itemBankDO1.setCheckerDate(new Date());//审核时间
                                        itemBankDO1.setState(1);//默认审核通过
                                    } else {
                                        //技能题导入时，会统一调至综合知识点
                                        KnowledgePointsDO knowledgePointsDO1 = knowledgePointsService
                                                .findOneByKv("profile_id", Long.parseLong(cprofileId), "name", "综合知识点", "pid", 0);
                                        itemBankDO1.setKpointsId(knowledgePointsDO1.getId());
                                        itemBankDO1.setState(0);//默认审核通过
                                    }
                                    itemBankDO1.setProfileId(Long.parseLong(cprofileId));//证书id
                                    itemBankDO1.setTopicContent(list.get(i).getTopicContent().trim());//题目内容
                                    itemBankDO1.setRightKey(list.get(i).getRightKey());//正确答案
                                    itemBankDO1.setTopicAnalysis(list.get(i).getTopicAnalysis());//题目解析
                                    itemBankDO1.setCreaterId(this.getUserId());//创建人
                                    itemBankDO1.setUpdaterId(this.getUserId());//修改人
                                    itemBankDO1.setItemBankType(itembankType);//题库类型（0练习题，1考试题）
                                    itemBankDO1.setTopicTypes(topicType);//题目类型（0单选，1多选，2判断，3实操）
                                    itemBankDO1.setType(type);//类型（0理论，1技能）
                                    String options="";
                                    if (StringUtils.isNotBlank(list.get(i).getOptionsA())) {
                                        options = "A、" + list.get(i).getOptionsA();
                                    }
                                    if (StringUtils.isNotBlank(list.get(i).getOptionsB())) {
                                        options = options + ";;B、" + list.get(i).getOptionsB();
                                    }
                                    if (StringUtils.isNotBlank(list.get(i).getOptionsC())) {
                                        options = options + ";;C、" + list.get(i).getOptionsC();
                                    }
                                    if (StringUtils.isNotBlank(list.get(i).getOptionsD())) {
                                        options = options + ";;D、" + list.get(i).getOptionsD();
                                    }
                                    if (StringUtils.isNotBlank(list.get(i).getOptionsE())) {
                                        options = options + ";;E、" + list.get(i).getOptionsE();
                                    }
                                    if (StringUtils.isNotBlank(list.get(i).getOptionsF())) {
                                        options = options + ";;F、" + list.get(i).getOptionsF();
                                    }
                                    itemBankDO1.setOptions(options);//答案选项
                                    itemBankDO1.setResourceType(0);
                                    bankDOList.add(itemBankDO1);
                                }
                            }
                        }
                    }
                }
            }


            if (sb.length() > 0) {
                ErrorCodeVo errorCodeVo = new ErrorCodeVo();
                errorCodeVo.setSeq(cout);
                cout += 1;
                errorCodeVo.setErrorCode(sb.toString());
                list1.add(errorCodeVo);
            }
        }

        if (list1.size() == 0) {
            boolean c = itemBankService.insertBatch(bankDOList, bankDOList.size());
            if (c) {
                return Result.ok("成功导入" + list.size() + "条数据");
            } else {
                return Result.fail("题目信息导入错误，请稍后重试或联系管理员");
            }
        } else {
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
            //将list1存到缓存中
            EhCacheUtil.put("itemBank" + this.getUserId(), jsonArray);
            return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
        }
    }

    /**
     * 导出错误信息
     *
     * @param request
     * @param response
     * @throws Exception
     * @author kl
     */
    @Log("导出错误信息")
    @GetMapping("/importError")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:itemBank:import")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("题库题目导入错误信息", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        String jsonArray = EhCacheUtil.get("itemBank" + this.getUserId()).toString();
        JSONArray arrayList = JSONArray.parseArray(jsonArray);
        //转换为目标对象list
        List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
        workbook.write(response.getOutputStream());
    }


}
